package com.gl.codewar.template;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

public class MakingWaves {

	public static String surf(String str) {

//		ArrayList<String> list = new ArrayList<String>();
		
		char[] charArray = str.toCharArray();
		String[][] result = new String[charArray.length][charArray.length];
		
		int size = charArray.length;
		
		int prevY = 0;
		
		for (int i = 0; i < size; i++) {
			Character ch = new Character(charArray[i]);
//			System.out.println(ch);
			
			int chInt = (int) ch.charValue();
//			System.out.println(chInt);
			
			if (i == 0) {				
				result[0][0] = String.valueOf(ch);
			} else {
				int prevChInt = (int) charArray[i-1];
				
				if (chInt > prevChInt) {
//					System.out.println(charArray[i] + " es mayor a " + charArray[i-1]);
					result[prevY+1][i]  = String.valueOf(ch);
					prevY++; 
				} else if (chInt < prevChInt) {
//					System.out.println(charArray[i] + " es menor a " + charArray[i-1]);
					if (prevY == 0) {
						result[prevY][i]  = String.valueOf(ch);
						
					}
					else {
						result[prevY-1][i]  = String.valueOf(ch);
						prevY--;
					}
					
					
				} else {
//					System.out.println(charArray[i] + " son iguales " + charArray[i-1]);
					result[prevY][i] = String.valueOf(ch);
				}
			}
		}
		
//		for () {
//			
//		}
		
//		result = Collections.reverse(new ArrayList<String[]>(result));
		
		System.out.println(print(result));
		return print(result);
	}

//	public static String getSpaces(int size) {
//		String str = "";
//		for (int i = 0; i < size; i++) {
//			str += " ";
//		}
//		return str;
//	}
//	
//	public static String fromTo(int from, int to) {
//		return getSpaces(to - from);
//	}
	
	public static String print(String[][] r) {
		
		String[] lineas = new String[r.length];
		String str="";
		
		for (int i = r.length - 1; i >= 0; i--) {
			String l = "";
			
			for (int j = 0; j < r[i].length; j++) {
				if (r[i][j] == null) {
					l+=" ";
				} else {
					l+=r[i][j];
				}
			}
			if (!l.trim().isEmpty()) {
				
				int spacesInDerecha = 0;
				
				char[] charArray = l.toCharArray();
				for (int x = charArray.length - 1; x >= 0 ; x--) {
					if (! String.valueOf(charArray[x]).equals(" ") ) {
						break;
					}
					spacesInDerecha++;
				}
				
				l = String.valueOf(Arrays.copyOfRange(charArray, 0, charArray.length - (spacesInDerecha) ));
						
				str += l + "\n";
			}
		}
		return str;
	}
}
